<template>
  <el-dialog
    class="set_dialog"
    width="500px"
    title="设置活动"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
  >
    <p class="text-center tip">您确定要设置该商品活动吗？</p>
    <el-form
      class="ruleForm"
      :model="form"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
    >
      <el-form-item
        label="商品活动"
        prop="reason"
      >
        <el-select
          v-model="form.activity"
          placeholder="请选择"
          multiple
        >
          <el-option
            v-for="item in activityList"
            :key="item.id"
            :label="item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div
      slot="footer"
      class="dialog-footer"
    >
      <el-button
        size="small"
        @click="dialogVisible = false"
      >取 消</el-button>
      <el-button
        size="small"
        type="primary"
        @click="submit"
      >确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getActivityList, addActivity } from "@/api/audit";
export default {
  data() {
    return {
      form: {
        activity: ""
      },
      rules: {
        activity: [
          { required: true, message: '请选择商品活动', trigger: 'change' }
        ]
      },
      dialogVisible: false,
      goodsId: null,
      activityList: []
    }
  },
  methods: {
    submit() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const params = {
            goods_id: this.goodsId,
            activity_type: this.form.activity.join(',')
          }
          addActivity(params).then(res => {
            this.dialogVisible = false;
            this.$emit('getList', true);
          });
        } else {
          this.$message({
            message: "请检查表单错误",
            type: "error"
          });
          return false;
        }
      });
    }
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        getActivityList(this.goodsId).then(res => {
          this.activityList = [];
          for (let key in res.activity_list) {
            this.activityList.push({
              id: key,
              label: res.activity_list[key]
            })
          };
          if (res.activity_type) {
            this.form.activity = res.activity_type.split(',');
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.tip {
  line-height: 35px;
  margin-bottom: 10px;
}
</style>
